from django.shortcuts import render, redirect, reverse, get_object_or_404, Http404
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from django.contrib.auth import get_user_model
from django.db.models import Q

from .models import Message
from main.views import text_to_markdown_without_p, safe_text


def get_users(request):
    user_objects = get_user_model().objects.all()
    users = []
    for user_object in user_objects:
        user = {
            'get_image_url': user_object.get_image_url(),
            'username': user_object.username,
            'id': user_object.id,
            'get_display': user_object.get_display(),
            'message_count': Message.objects.filter(sender_id=user_object.id,
                                                    receiver_id=request.user.id,
                                                    read=False).count(),
        }
        users.append(user)
    users.sort(key=lambda x: x.get('message_count', 0), reverse=True)
    return users


def get_messages(messages):
    result = []
    for message in messages:
        result.append({
            'id': message.id,
            'time': message.time,
            'sender': message.sender,
            'sender_id': message.sender_id,
            'content': text_to_markdown_without_p(message.content),
        })
    return result


@login_required
def public(request):
    public_messages = Message.objects.filter(receiver__isnull=True)
    users = get_users(request)
    context = {
        'public_messages': get_messages(public_messages),
        'users': users,
        'receiver_id': -1,
        'page_chat': True,
    }
    return render(request, 'chat/public.html', context=context)


@login_required
def private(request, receiver_id):
    receiver = get_object_or_404(get_user_model(), id=receiver_id)
    user_id = request.user.id
    messages = Message.objects.filter((Q(sender_id=user_id) & Q(receiver_id=receiver_id)) |
                                      (Q(sender_id=receiver_id) & Q(receiver_id=user_id)))
    for message in messages:
        if message.receiver == request.user:
            message.read = True
            message.save()
    users = get_users(request)
    context = {
        'messages': get_messages(messages),
        'users': users,
        'receiver': receiver,
        'page_chat': True,
    }
    return render(request, 'chat/private.html', context=context)


@login_required
@require_POST
def send(request):
    data = request.POST
    sender = request.user
    receiver_id = data.get('receiver-id')
    receiver = get_user_model().objects.filter(id=receiver_id).first()
    if receiver == sender.identity:  # sender不是教徒不能发送公共消息
        raise Http404
    content = safe_text(data.get('content', '').strip())
    if 0 < len(content) <= 10000:
        Message.objects.create(sender=sender, receiver=receiver, content=content)
    if receiver:
        return redirect(reverse('chat:private', args=(receiver_id, )))
    return redirect(reverse('chat:public'))


@login_required
def withdraw(request, message_id):
    message = get_object_or_404(Message.objects.filter(sender=request.user), id=message_id)
    message.delete()
    receiver_id = request.GET.get('id')
    receiver = get_user_model().objects.filter(id=receiver_id).first()
    if receiver:
        return redirect(reverse('chat:private', args=(receiver_id, )))
    return redirect(reverse('chat:public'))


@login_required
@require_POST
def change_background_view(request):
    background = request.FILES.get('background')
    data = request.POST
    receiver_id = data.get('receiver-id')
    receiver = get_user_model().objects.filter(id=receiver_id).first()
    if background is not None:
        request.user.background = background
        request.user.save()
    else:
        raise Http404
    if receiver:
        return redirect(reverse('chat:private', args=(receiver_id, )))
    return redirect(reverse('chat:public'))
